import 'package:flutter/material.dart';

class RefreshableListView extends StatefulWidget {
  final Future<void> Function() onRefresh;
  final Future<void> Function()? onLoadMore; // 可选的加载更多回调
  final List<Widget> children;
  final bool enableLoadMore; // 控制上拉加载功能的开关

  const RefreshableListView({
    required this.onRefresh,
    required this.children,
    this.onLoadMore,
    this.enableLoadMore = false, // 默认不启用上拉加载
    super.key,
  });

  @override
  _RefreshableListViewState createState() => _RefreshableListViewState();
}

class _RefreshableListViewState extends State<RefreshableListView> {
  late ScrollController _scrollController;
  bool _isLoadingMore = false;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController()..addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  /// 滚动监听
  void _onScroll() {
    if (widget.enableLoadMore &&
        !_isLoadingMore &&
        _scrollController.position.pixels >=
            _scrollController.position.maxScrollExtent) {
      _loadMore();
    }
  }

  Future<void> _loadMore() async {
    if (_isLoadingMore || widget.onLoadMore == null) {
      return; // 防止重复加载和检查是否有加载更多的回调
    }
    setState(() {
      _isLoadingMore = true;
    });
    await widget.onLoadMore!(); // 调用加载更多的回调
    setState(() {
      _isLoadingMore = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: widget.onRefresh,
      child: widget.children.isEmpty
          ? const Center(
              child: Text('暂无数据'),
            )
          : ListView(
              controller: _scrollController,
              physics: const AlwaysScrollableScrollPhysics(),
              children: [
                ...widget.children,
                if (_isLoadingMore && widget.enableLoadMore)
                  const Center(
                      child: CircularProgressIndicator(strokeWidth: 2)),
              ],
            ),
    );
  }
}
